package service;

import dataAcsessObject.Exception.NotEntityFoundException;
import dataAcsessObject.JPADAOFactory;
import entity.Category;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import service.exception.ObjectNotFoundException;
import valueObject.CategoryVO;

/**
 *
 * @author Juan Hernández Serrato
 */
public class CategoryService extends AbstractService<CategoryVO, Category> {

    @Override
    public void create(CategoryVO valueObject, EntityManager em) {
        JPADAOFactory.getInstance().getCategoryDAO().create(valueObject.toEntity(), em);
    }

    @Override
    public void update(CategoryVO valueObject, EntityManager em) throws ObjectNotFoundException {
        try {
            Category category = JPADAOFactory.getInstance().getCategoryDAO().findById(valueObject.getId(), em);
            category = valueObject.toEntity();
            JPADAOFactory.getInstance().getCategoryDAO().update(category, em);
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public void delete(Object id, EntityManager em) throws ObjectNotFoundException {
        try {
            Category category = JPADAOFactory.getInstance().getCategoryDAO().findById(id, em);
            JPADAOFactory.getInstance().getCategoryDAO().delete(category, em);
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public CategoryVO findById(Object id, EntityManager em) throws ObjectNotFoundException {
        try {
            return JPADAOFactory.getInstance().getCategoryDAO().findById(id, em).toValueObject();
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public List<CategoryVO> findAll(EntityManager em) {
        List<CategoryVO> categoryVOs = new ArrayList<CategoryVO>();
        List<Category> categorys = JPADAOFactory.getInstance().getCategoryDAO().findAll(em);
        for (Category category : categorys) {
            categoryVOs.add(category.toValueObject());
        }
        return categoryVOs;
    }

    @Override
    public List<CategoryVO> findRange(int begin, int end, EntityManager em) {
        List<CategoryVO> categoryVOs = new ArrayList<CategoryVO>();
        List<Category> categorys = JPADAOFactory.getInstance().getCategoryDAO().findRange(begin, end, em);
        for (Category category : categorys) {
            categoryVOs.add(category.toValueObject());
        }
        return categoryVOs;
    }

}
